package com.anon_soft.anon_edit;

/**
 * 
 * This activity is currently the default activity
 * and acts as the edit view.
 * 
 */


import java.io.File;
import java.io.IOException;
import java.util.Vector;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ActionBar.Tab;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

public class AEEditorActivity extends Activity {
	
	private String	TAG = "AEEditorActivity";
	private String	DEFAULT_DIR = "/sdcard";
	private	Uri		mCurrentTabSaveFilePath;
	private boolean mExternalStorageAvailable = false;
	private boolean mExternalStorageWriteable = false;
	

	private int		untitledFileCount = 1;
	
	private ActionBar ab;
//	private CodeEditFragment f; 
//	private CodeEditFragment f2;
//	private CodeEditFragment f3;
	
	// Used to store CodeEditFragments for interaction with their
	// ASEditText objects
	private Vector<CodeEditFragment>		tabVector;
	
	/*
	 * Trying to redo this code to find the following bugs:
	 * 
	 * - The bundle which includes the passed id in the 
	 *   newInstance method in CodeEditFragment does not
	 *   get transferred to the CodeEditFragment object's
	 *   onCreate() method, it just receives NULL.  Why!?!?
	 *   
	 * - Activity recreation makes a mess of the tab contents.
	 * 
	 */
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.main);
		
		ab = getActionBar();
        ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        
        tabVector = new Vector<CodeEditFragment>();
        
        
        /* test code
        f = CodeEditFragment.newInstance(1);
        if ( f.getArguments() == null )
        	Log.i(TAG, "f.getArguments() is null!");
        else
        {
        	Log.i(TAG, "f.getArguments().getInt = " + f.getArguments().getInt("m_id"));
        }
        f.setRetainInstance(true);
        ab.addTab(ab.newTab().setText(R.string.tab1).setTabListener(new editActionbarTabListener(f)));
        
        f2 = CodeEditFragment.newInstance(2);
        f2.setRetainInstance(true);
        ab.addTab(ab.newTab().setText(R.string.tab2).setTabListener(new editActionbarTabListener(f2)));

        f3 = CodeEditFragment.newInstance(3);
        f3.setRetainInstance(true);
        ab.addTab(ab.newTab().setText(R.string.tab3).setTabListener(new editActionbarTabListener(f3)));
        */
        
        Log.i(TAG, "AAAAA | onCreate");
		
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
		Log.i(TAG, "AAAAA | onDestroy");
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		
		Log.i(TAG, "AAAAA | onPause");
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		Log.i(TAG, "AAAAA | onResume");
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		
		Log.i(TAG, "AAAAA | onStop");
	} 
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		
		Log.i(TAG, "AAAAA | onSaveInstanceState");
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		
		MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.main_menu, menu);

		
		return super.onCreateOptionsMenu(menu);
	}
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch (item.getItemId()) {
		    case R.id.newMenuItem:
		        newFileSelected();
		        return true;
		    case R.id.openMenuItem:
		        openFileSelected();
		        return true;
		    case R.id.saveMenuItem:
		    	saveCurrentTabSelected();
		    	return true;
		    case R.id.saveAsMenuItem:
		    	saveCurrentTabAsSelected();
		    	return true;
		    case R.id.closeTabMenuItem:
		    	closeCurrentTabSelected();
		    	return true;
		    case R.id.exitMenuItem:
		    	exitApplicationSelected();
		    	return true;
		    default:
		        return super.onOptionsItemSelected(item);
	    }
	}
	
	/**
	 * Creates a new tab.
	 */
	public void newFileSelected()
	{
		Uri						fileUri;
		Uri.Builder				fileUriBuilder = new Uri.Builder();
		String					fileName;
		int						nextTabID = ab.getTabCount();
		CodeEditFragment		tempTabFragment = CodeEditFragment.newInstance(nextTabID);
		
		fileName = getString(R.string.untitledTabTitle) + " " + Integer.toString(untitledFileCount);
		
		fileUriBuilder.appendEncodedPath(DEFAULT_DIR);
		fileUriBuilder.appendEncodedPath(fileName);
		fileUri = fileUriBuilder.build();
		
		tempTabFragment.setFragmentFileUri(fileUri);
		
		tabVector.add(nextTabID, tempTabFragment);
		
		ab.addTab(ab.newTab().setText(fileName).setTabListener(new editActionbarTabListener(tempTabFragment)));
		ab.setSelectedNavigationItem(ab.getNavigationItemCount() - 1);
		
		untitledFileCount++;
		nextTabID++;
		
		/*
		if (ab.getTabCount() > 0)
		{
			Log.i(TAG, "AAAAA First tab text is: " + ab.getTabAt(0).getText());
			ab.getTabAt(0).setText(ab.getTabAt(0).getText() + "1");
			Log.i(TAG, "AAAAA Now the first tab text is: : " + ab.getTabAt(0).getText());
		}
		*/
		
	}
	
	/**
	 * Opens a open file dialog and attempts to open the selected file.
	 * 
	 * - Open an OI file picker intent
	 * - Open file, create new tab, CodeEditFragment, etc. *
	 * 
	 * NOTE: * sections will be handled in the onActivityResult method
	 */
	public void openFileSelected()
	{
		
	}
	
	/**
	 * Saves the currently selected tab to a file.  It performs the following steps:
	 * 
	 * - It checks to see if the CodeEditFragment has an actual file Uri
	 *   - If it does not, present an OI file picker dialog
	 *   	- Check to see if the chosen file already exists *
	 *        - If it does, make sure it is acceptable to overwrite it *
	 *          - Save file *
	 *        - If it does not, then save the file *
	 *      - Save chosen Uri in the CodeEditFragment *
	 *   - If it does, then save the file
	 *   
	 * NOTE: * sections will be handled in the onActivityResult method
	 */
	public void saveCurrentTabSelected()
	{
		
	}
	
	/**
	 * Saves the currently selected tab, but it gives you the chance to change
	 * the location and file name.
	 * 
	 * - Open an OI file picker so that user can choose location and file
	 *   - If file exists make sure that it is acceptable to overwrite it *
	 *     - Save file *
	 *   - If it does not, then save file *
	 *   - Save chosen Uri in the CodeEditFragment *
	 */
	public void saveCurrentTabAsSelected()
	{
		Intent intent = new Intent("org.openintents.action.PICK_FILE");
		intent.setData(Uri.parse("file:///sdcard/"));
		intent.putExtra("org.openintents.extra.TITLE", "Save your file as ...");
		startActivityForResult(intent, 224);
	}
	
	/**
	 * Closes a tab
	 * 
	 * - Check to see if the tab has been saved yet
	 *   - If it has not, save the tab
	 *      - Check to see if the tab has been given a proper name yet
	 *        - If it has not, then let the user select a location and filename
	 *          - Check to see if the file already exists
	 *            - If it does, then ask the user if it is ok to overwrite it
	 *              - If it is, then save the file
	 *              - If it is not, then ask the user for another file.  Got back to the above
	 *            - If it does not exist, then save the file
	 *        - If it has, then save the file
	 *   - If it has, then close the tab
	 */
	public void closeCurrentTabSelected()
	{
		int		currentTabIndex = ab.getSelectedNavigationIndex();
		Tab		currentTab = ab.getTabAt(currentTabIndex);
		
		if ( ((CodeEditFragment) tabVector.get(currentTabIndex)).doesASEditTextNeedToBeSaved() == true )
		{
			// Save content's of the current fragment's ASEditText
		}
		
		// Remove tab
		if ( ab.getTabCount() > 0 )
			ab.removeTab(currentTab);
		
		// Remove CodeEditFragment from tabVector
		tabVector.remove(currentTabIndex);
	}
	
	/*
	 * String		fPath;
		File		f;
		
		if ( m_fUri == null )
			return false;
		else
			fPath = m_fUri.getPath();
		
		if ( fPath == null )
			return false;
		
		f = new File(fPath);
		
		try
		{
			// Check if overwriting a file is acceptable
			if ( checkIfFileExists == true )
			{
				if ( f.exists() == true )
				{
					// file alread exists, ask if over=writing
					// is acceptable!
				}
			}
			
			if ( f.createNewFile() == false )
			{
				return false;
			}
			
			
		}
		catch ( IOException e )
		{
			Log.e(TAG, e.toString());
			return false;
		}
		
		return true;
	 */
	
	public void exitApplicationSelected()
	{
		
	}
	
	public void changeTabTitle(int tabPosition, String text)
	{
		int					currentTabIndex = tabPosition;
		String				currentTabTitle;
		
		currentTabTitle = (String) ab.getTabAt(currentTabIndex).getText();		// just to check
		ab.getTabAt(currentTabIndex).setText(text);		// change tab title
		currentTabTitle = (String) ab.getTabAt(currentTabIndex).getText();		// just to check
	}
	
	/**
	 * Changes the tab title of the currently selected tab to the last
	 * path segment in the internal variable of mCurrentTabSaveFilePath
	 */
	public void changeTabTitle()
	{
		int					currentTabIndex = ab.getSelectedNavigationIndex();
		String				currentTabTitle;
		
		if ( this.mCurrentTabSaveFilePath == null )
			return;
		
		currentTabTitle = (String) ab.getTabAt(currentTabIndex).getText();		// just to check
		ab.getTabAt(currentTabIndex).setText(this.mCurrentTabSaveFilePath.getLastPathSegment());		// change tab title
		currentTabTitle = (String) ab.getTabAt(currentTabIndex).getText();		// just to check
	}
	
	public void saveCurrentTabAs(Uri	fUri)
	{
		CodeEditFragment 	cef;
		int					currentTabIndex = ab.getSelectedNavigationIndex();
		
		if ( fUri == null )
			return;
		
		cef = (tabVector.get(ab.getSelectedNavigationIndex()));
		cef.setFragmentFileUri(fUri);
		cef.saveASEditText();
	}
	
	public void saveCurrentTabAs()
	{
		CodeEditFragment 	cef;
		Bundle				b;
		int					currentTabIndex = ab.getSelectedNavigationIndex();
		
		if ( this.mCurrentTabSaveFilePath == null )
			return;
		
		cef = (tabVector.get(ab.getSelectedNavigationIndex()));
		cef.setFragmentFileUri(this.mCurrentTabSaveFilePath);
		cef.saveASEditText();
	}

	/**
	 * This method gets called after calling another activity for
	 * a result.  
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		
		Uri					fileURI;
		CodeEditFragment 	cef;
		String				fileName;
		int					currentTabIndex = ab.getSelectedNavigationIndex();
		Bundle				b;
		
		Log.i(TAG, "AAAAA onActivityResult");
		
		if ( resultCode == RESULT_OK )
		{
			fileURI = data.getData();
			cef = (tabVector.get(ab.getSelectedNavigationIndex()));
			
			Log.i(TAG, "AAAAA onActivityResult | resultCode is RESULT_OK | fileURI is " + fileURI);
			
			if ( fileURI == null )
				return;
			
			if ( requestCode == 224 )
			{
				// 224 == Save as
				Log.i(TAG, "AAAAA requestCode is 224");
				fileName = fileURI.getLastPathSegment();
				Log.i(TAG, "AAAAA fileName = " + fileName);
				
				/*
				 * TODO:  The proceeding code does not change the current tab's 
				 * 		  text.  Even though when you grab the text after it is
				 * 		  "set" it returns what I have set it to.  This is very 
				 * 		  confusion.
				 * 
				 * 		  Also, this code should be placed at the end of this
				 * 		  segment.  Also, need to check if the file already 
				 * 		  exists.  
				 */
				
				/*
				 * If the selected file exists, then ak if it's ok to overwrite 
				 * it or not.  Both cases are handled in the dialog handling
				 * methods including getting a new file name and saving the 
				 * file and changing tab title.
				 */
				if ( cef.fileUriExists(fileURI) )
				{
					// File exists should we over-write this?
					this.mCurrentTabSaveFilePath = fileURI;
					b = new Bundle();
					b.putInt("saveTab", currentTabIndex);
					this.showDialog(224, b);				
				}
				else
				{
					/*
					 * If the selected file does not exist, then save the file
					 * and change the tab title.
					 */
					saveCurrentTabAs(fileURI);
					changeTabTitle(currentTabIndex, fileName);
				}
			}
			else if ( requestCode == 225 )
			{
				// 225 == Save
				Log.i(TAG, "AAAAA requestCode is 225");
				cef.saveASEditText();
			}
			else if ( requestCode == 226 )
			{
				// 226 == open file
				Log.i(TAG, "AAAAA requestCode is 226");
			}
		}
	}
	
	protected void checkExternalStorage()
	{
		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
		    // We can read and write the media
		    mExternalStorageAvailable = mExternalStorageWriteable = true;
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
		    // We can only read the media
		    mExternalStorageAvailable = true;
		    mExternalStorageWriteable = false;
		} else {
		    // Something else is wrong. It may be one of many other states, but all we need
		    //  to know is we can neither read nor write
		    mExternalStorageAvailable = mExternalStorageWriteable = false;
		}
	}

	/**
	 * Create the various dialogs used through this app
	 * 
	 * id explanations:
	 * 
	 * 224:  Over-write file dialog
	 */
	@Override
	protected Dialog onCreateDialog(int id, Bundle args) 
	{
		switch (id)
		{
			case 224:	// Over-write file from a Save-As command
				AlertDialog.Builder b = new AlertDialog.Builder(this);
				b.setMessage("This file already exists.  Over-write it?")
				 .setCancelable(false)
				 .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						AEEditorActivity.this.saveCurrentTabAs();
					}
				 })
				 .setNegativeButton("No", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// Don't over-write, go back to the beginning
						AEEditorActivity.this.saveCurrentTabAsSelected();
						AEEditorActivity.this.changeTabTitle();
					}
				});
				AlertDialog alert = b.create();
				return alert; 
			default:
				return super.onCreateDialog(id);
		}
	}
	
}